<script setup lang='ts' name="housing-resources">
import type { VxeGridInstance, VxeGridListeners } from 'vxe-table'

import { flowHttp } from '@fl/api/work-flow'
import ButtonItem from '@fl/components/button-item.vue'
import { ElButton, ElCard, ElCol, ElForm, ElFormItem, ElInput, ElOption, ElRow } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

import type { IRowV0 } from './types'

import DetailItem from './component/detail.vue'
import TagItem from './component/tagItem.vue'
import { useDicts } from './hooks/use-dicts'
import { useTable } from './hooks/use-table'

const { dicts } = useDicts()
const { btns, gridOptions, searchBtns, useFilter } = useTable()

const state = {
    CreatedName: '',
    dany_Id: '',
    dongbh_Id: '',
    fangh: '',
    huxxx: '',
    louc: '',
    shangjspzt: '',
    suosqy_Id: '',
    xiangmmc_Id: '',
    zullx: '',
}

const form = ref({
    ...state,
})

function reset() {
    btnRef.value.reset()
    form.value = {
        ...state,
    }
    getData()
}
const router = useRouter()
let detail = reactive<any>({})
const show = ref(true)
const detailItemRef = ref()
const btnRef = ref()
const xGrid = ref<VxeGridInstance<IRowV0>>()

const gridEvents: VxeGridListeners<IRowV0> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
        }
        getData()
    },
}

async function getData() {
    gridOptions.loading = true
    const { currentPage, pageSize } = gridOptions.pagerConfig

    const res = await queryData({
        filter: useFilter(form.value),
        pageInfo: {
            page: currentPage,
            size: pageSize,
        },
    })
    gridOptions.loading = false
    // TODO: 同工作流网关 企业机构管理 租赁管理 后端返回数据结构不一致 res拦截器不做统一处理
    const { data: { data } } = res
    gridOptions.pagerConfig.total = data.PagingInfo.DataCount
    gridOptions.data = data.Datas
}

async function queryData(params: any) {
    return await flowHttp('query', {
        body: {
            data: {
                code: 'ad91b0d88fa11097', // 房源code dev pro 写死
                ...params,
            },
        },
    })
}

async function doSearch(item: any) {
    console.log('doSearch', item)
    form.value.shangjspzt = item.value === 'all' ? '' : item.label
    getData()
}

async function doAction(item: any, row?: any) {
    switch (item.value) {
        case 1:
            router.push({
                path: 'housing-resources-detail',
                query: {
                    ObjectID: row.ObjectID,
                },
            })
            break
        case 'view':
            detail = cloneDeep(row)
            show.value = false
            break
        default:
            break
    }
}

function filterBtn(row: any) {
    // TODO: 接口无id返回
    return row.shangjspzt === '审批中' ? btns : [btns[0]] as any
}

function doApproval() {
}

function toggleAllCheckboxEvent() {
    const $grid = xGrid.value
    if ($grid)
        $grid.toggleAllCheckboxRow()
}

function toggleCheckboxEvent(row) {
    const $grid = xGrid.value
    if ($grid)
        $grid.toggleCheckboxRow(row)
}

watch(show, (val: boolean) => {
    if (val)
        reset()
})

getData()

// TODO: 后端无接口 需要前端收集下拉选项值
async function initDicts() {
    const res = await queryData({
        pageInfo: {
            page: 1,
            size: 999,
        },
    })
    const { Datas = [] } = res
    const keys: any = [
        {
            label: 'suosqy',
            value: 'suosqy_Id',
        },
        {
            label: 'xiangmmc',
            value: 'xiangmmc_Id',
        },
        {
            label: 'dongbh',
            value: 'dongbh_Id',
        },
        {
            label: 'dany',
            value: 'dany_Id',
        },
        {
            label: 'louc',
            value: 'louc',
        },
    ]

    keys.forEach((key: any) => {
        const { label, value } = key
        dicts[value] = []
        Datas.forEach((data: any) => {
            const flag = dicts[value].some((v: any) => v.value === data[value])
            if (!flag && data[label]) {
                dicts[value].push({
                    label: data[label],
                    value: data[value] || data[label],
                })
            }
        })
    })
}
initDicts()
</script>

<template>
    <template v-if="show">
        <ElCard mb-20>
            <ElForm :inline="true"
                    :model="form"
                    label-width="100"
                    class="query_form"
            >
                <ElRow>
                    <ElCol :span="22">
                        <ElFormItem label="所属企业">
                            <ElSelect v-model="form.suosqy_Id"
                                      placeholder="请选择"

                                      value-key="value"
                                      clearable
                                      filterable
                            >
                                <ElOption v-for="item in dicts.suosqy_Id"
                                          :key="item.value"
                                          :label="item.label"
                                          :value="item.value"
                                />
                            </ElSelect>
                        </ElFormItem>

                        <ElFormItem label="所属项目">
                            <ElSelect v-model="form.xiangmmc_Id"
                                      filterable
                                      value-key="value"
                                      placeholder="请选择"
                                      clearable
                            >
                                <ElOption v-for="item in dicts.xiangmmc_Id"
                                          :key="item.value"
                                          :label="item.label"
                                          :value="item.value"
                                />
                            </ElSelect>
                        </ElFormItem>

                        <ElFormItem label="楼栋">
                            <ElSelect v-model="form.dongbh_Id"
                                      placeholder="请选择"
                                      clearable
                            >
                                <ElOption v-for="item in dicts.dongbh_Id"
                                          :key="item.value"
                                          :label="item.label"
                                          :value="item.value"
                                />
                            </ElSelect>
                        </ElFormItem>

                        <ElFormItem label="单元">
                            <ElSelect v-model="form.dany_Id"
                                      placeholder="请选择"
                                      clearable
                            >
                                <ElOption v-for="item in dicts.dany_Id"
                                          :key="item.value"
                                          :label="item.label"
                                          :value="item.value"
                                />
                            </ElSelect>
                        </ElFormItem>

                        <ElFormItem label="楼层">
                            <ElSelect v-model="form.louc"
                                      placeholder="请选择"
                                      clearable
                            >
                                <ElOption v-for="item in dicts.louc"
                                          :key="item.value"
                                          :label="item.label"
                                          :value="item.value"
                                />
                            </ElSelect>
                        </ElFormItem>

                        <ElFormItem label="房号">
                            <ElInput v-model="form.fangh"
                                     placeholder="请输入"
                                     clearable
                            />
                        </ElFormItem>

                        <ElFormItem label="租赁类型">
                            <ElSelect v-model="form.zullx"
                                      placeholder="请选择"
                                      clearable
                            >
                                <ElOption v-for="item in dicts.zullx"
                                          :key="item.value"
                                          :label="item.label"
                                          :value="item.value"
                                />
                            </ElSelect>
                        </ElFormItem>

                        <ElFormItem label="创建人">
                            <ElInput v-model="form.CreatedName"
                                     placeholder="请输入"
                                     clearable
                            />
                        </ElFormItem>
                    </ElCol>

                    <ElCol :span="2">
                        <ElFormItem>
                            <ElButton type="primary"
                                      @click="getData"
                            >
                                搜索
                            </ElButton>

                            <ElButton @click="reset">
                                重置
                            </ElButton>
                        </ElFormItem>
                    </ElCol>
                </ElRow>

                <ElRow style="border-top: 1px solid #e0e3e9;margin-bottom: 16px;" />

                <ElFormItem label="上架审批状态">
                    <ButtonItem ref="btnRef"
                                :active="true"
                                :btns="searchBtns"
                                @btn-click="doSearch($event)"
                    />
                </ElFormItem>
            </ElForm>
        </ElCard>

        <ElCard>
            <div class="mb-20">
                <ElButton @click="doApproval">
                    批量审批
                </ElButton>
            </div>
            <!-- 列表 -->
            <vxe-grid ref="xGrid"
                      v-bind="gridOptions"
                      v-on="gridEvents"
            >
                <template #checkbox_header="{ checked, indeterminate }">
                    <span class="custom-checkbox"
                          @click.stop="toggleAllCheckboxEvent"
                    >
                        <i v-if="indeterminate"
                           class="vxe-icon-square-minus-fill"
                        />

                        <i v-else-if="checked"
                           class="vxe-icon-square-checked-fill"
                        />

                        <i v-else
                           class="vxe-icon-checkbox-unchecked"
                        />
                    </span>
                </template>

                <template #checkbox_cell="{ row, checked, indeterminate }">
                    <span class="custom-checkbox"
                          @click.stop="toggleCheckboxEvent(row)"
                    >
                        <i v-if="indeterminate"
                           class="vxe-icon-square-minus-fill"
                        />

                        <i v-else-if="checked"
                           class="vxe-icon-square-checked-fill"
                        />

                        <i v-else
                           class="vxe-icon-checkbox-unchecked"
                        />
                    </span>
                </template>

                <template #shangjspzt="{ row }">
                    <div class="flex gap-2">
                        <TagItem dict-key="status"
                                 :label="row.shangjspzt"
                        />
                    </div>
                </template>

                <template #createdTime="{ row }">
                    {{ row.createdTime ? row.createdTime.replace('T', ' ') : '' }}
                </template>

                <template #operate="{ row }">
                    <ButtonItem :btns="filterBtn(row)"
                                @btn-click="doAction($event, row)"
                    />
                </template>
            </vxe-grid>
        </ElCard>
    </template>

    <DetailItem v-else
                ref="detailItemRef"
                v-model="show"
                :data="detail"
                @confirm="getData"
    />
</template>

<style lang="less" scoped>
.query_form {
    :deep(.el-form-item__content) {
        width: 250px;
    }
}
</style>
